package com.ruoyi.web.controller.system;

import com.fasterxml.jackson.core.type.TypeReference;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.JsonUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.Franchiser;
import com.ruoyi.system.domain.ProxyRecord;
import com.ruoyi.system.mapper.ProxyRecordMapper;
import com.ruoyi.system.service.IFranchiserService;
import com.ruoyi.system.service.IPlayerCostLogService;
import com.ruoyi.system.service.IProxyRecordService;
import com.ruoyi.web.controller.domain.MarksIdsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 代理发放记录Controller
 *
 * @author ruoyi
 * @date 2024-07-18
 */
@RestController
@RequestMapping("/system/record")
public class ProxyRecordController extends BaseController {
    @Autowired
    private IProxyRecordService proxyRecordService;
    @Autowired
    private ProxyRecordMapper proxyRecordMapper;
    @Autowired
    private IPlayerCostLogService playerCostLogService;
    @Autowired
    private IFranchiserService franchiserService;
    @Autowired
    private RedisCache redisCache;

    @PreAuthorize("@ss.hasAnyRoles('custom_admin,custom_common,custom_seller')")
    @GetMapping("/list")
    public TableDataInfo list(ProxyRecord proxyRecord) {
        startPage();
        List<ProxyRecord> list = proxyRecordService.selectProxyRecordList(proxyRecord);
        list.sort(Comparator.comparing(ProxyRecord::getTime));
        return getDataTable(list);
    }

    // 分销商-查询代理发放记录
    @PreAuthorize("@ss.hasAnyRoles('custom_admin,custom_common,custom_seller')")
    @GetMapping("/franchiser_list_record")
    public Object franchiserListRecord(ProxyRecord proxyRecord) {
        startPage();

        String username = SecurityUtils.getUsername();
        // TODO 这里可以保存到 sysuser数据中
        Franchiser mainFranchiser = new Franchiser();
        mainFranchiser.setPhone(username);
        mainFranchiser.setPrimaryId(0L);
        List<Franchiser> franchiserList = franchiserService.selectFranchiserList(mainFranchiser);
        mainFranchiser = franchiserList.get(0);

        List<ProxyRecord> proxyRecordList = new ArrayList<>();
        if (proxyRecord.getTargetId() != null) {
            if (proxyRecord.getTargetId() == (long) mainFranchiser.getFranchiserId()) {
                // nothing
            } else {
                Franchiser fuFranchiser = new Franchiser();
                fuFranchiser.setFranchiserId(proxyRecord.getTargetId());
                List<Franchiser> fuFranchiserList = franchiserService.selectFranchiserList(fuFranchiser);
                if (fuFranchiserList == null || fuFranchiserList.isEmpty()) {
                    return error("You do not have permission to add this ID.");
                }
                if (fuFranchiserList.get(0).getPrimaryId() != (long) mainFranchiser.getFranchiserId()) {
                    return error("You do not have permission to add this ID.");
                }
            }
            proxyRecordList = proxyRecordService.selectProxyRecordList(proxyRecord);
        } else {
            proxyRecord.setTargetId(mainFranchiser.getFranchiserId());

            proxyRecordList = proxyRecordService.selectProxyRecordList(proxyRecord);
            String key = "marks:" + username;
            String value = redisCache.getCacheObject(key);
            if (value != null) {
                List<String> ids = JsonUtil.deserialize(value, new TypeReference<List<String>>() {
                });
                for (String strId : ids) {
                    long franchiserId = Long.parseLong(strId);
                    if (franchiserId == mainFranchiser.getFranchiserId()) {
                        continue;
                    }
                    proxyRecord.setTargetId(franchiserId);
                    proxyRecordList.addAll(proxyRecordService.selectProxyRecordList(proxyRecord));
                }
            }
        }
        proxyRecordList.sort(Comparator.comparing(ProxyRecord::getTime).reversed());
        return getDataTable(proxyRecordList);
    }

    @PreAuthorize("@ss.hasAnyRoles('custom_admin,custom_common,custom_seller')")
    @GetMapping("/franchiser_marks_ids")
    public Object franchiserMarksIds(MarksIdsVo vo) {
        String username = SecurityUtils.getUsername();
        // TODO 这里可以保存到 sysuser数据中
        Franchiser mainFranchiser = new Franchiser();
        mainFranchiser.setPhone(username);
        mainFranchiser.setPrimaryId(0L);
        List<Franchiser> franchiserList = franchiserService.selectFranchiserList(mainFranchiser);
        mainFranchiser = franchiserList.get(0);

        List<String> ids = JsonUtil.deserialize(vo.ids, new TypeReference<List<String>>() {
        });
        for (String id : ids) {
            if (id.equals("" + mainFranchiser.getFranchiserId())) {
                // nothing
            } else {
                Franchiser fuFranchiser = new Franchiser();
                fuFranchiser.setFranchiserId(Long.parseLong(id));
                List<Franchiser> fuFranchiserList = franchiserService.selectFranchiserList(fuFranchiser);
                if (fuFranchiserList == null || fuFranchiserList.isEmpty()) {
                    return error("You do not have permission to add this ID.");
                }
                if (fuFranchiserList.get(0).getPrimaryId() != (long) mainFranchiser.getFranchiserId()) {
                    return error("You do not have permission to add this ID.");
                }
            }
        }

        String key = "marks:" + username;
        redisCache.setCacheObject(key, vo.ids);

        return success();
    }

    @PreAuthorize("@ss.hasAnyRoles('custom_admin,custom_common,custom_seller')")
    @GetMapping("/franchiser_get_marks_ids")
    public Object franchiserGetMarksIds(MarksIdsVo vo) {
        String username = SecurityUtils.getUsername();

        String key = "marks:" + username;
        String value = redisCache.getCacheObject(key);
        Map<String, String> data = new HashMap<>();
        data.put("ids", value != null ? value : "[]");
        return data;
    }


    // 统计数据
    @PreAuthorize("@ss.hasAnyRoles('custom_admin,custom_common,custom_seller')")
    @GetMapping("/stat")
    public Object stat(ProxyRecord proxyRecord) {
        List<Franchiser> allFranchiserList = franchiserService.selectFranchiserList(new Franchiser());

        List<ProxyRecord> list = proxyRecordService.selectProxyRecordList(proxyRecord);
        long totalSendCount = 0;
        Set<Long> playerSet = new HashSet<>();
        Set<Long> mainPlayerSet = new HashSet<>();
        for (ProxyRecord record : list) {
            totalSendCount += record.getValue();
            playerSet.add(record.getTargetId());

            Franchiser franchiser = Helper.findFranchiser(allFranchiserList, record.getTargetId());
            if (franchiser != null && franchiser.getPrimaryId() == 0 && franchiser.getLevel() == 2) {
                mainPlayerSet.add(record.getTargetId());
            }
        }

        Map<String, Long> res = new HashMap<>();
        res.put("totalSendCount", totalSendCount);
        res.put("totalSendPeopleCount", (long) playerSet.size());
        res.put("totalSendMainNumberCount", (long) mainPlayerSet.size());
        return res;
    }

    //    @PreAuthorize("@ss.hasPermi('system:record:export')")
    @PreAuthorize("@ss.hasAnyRoles('custom_admin,custom_common,custom_seller')")
    @Log(title = "代理发放记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ProxyRecord proxyRecord) {
        List<ProxyRecord> list = proxyRecordService.selectProxyRecordList(proxyRecord);
        ExcelUtil<ProxyRecord> util = new ExcelUtil<ProxyRecord>(ProxyRecord.class);
        util.exportExcel(response, list, "代理发放记录数据");
    }

    /**
     * 获取代理发放记录详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:record:query')")
    @PreAuthorize("@ss.hasAnyRoles('custom_admin,custom_common,custom_seller')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(proxyRecordService.selectProxyRecordById(id));
    }

    //    @PreAuthorize("@ss.hasPermi('system:record:add')")
    @PreAuthorize("@ss.hasAnyRoles('custom_admin,custom_common,custom_seller')")
    @Log(title = "代理发放记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProxyRecord proxyRecord) {
        return toAjax(proxyRecordService.insertProxyRecord(proxyRecord));
    }

    /**
     * 修改代理发放记录
     */
//    @PreAuthorize("@ss.hasPermi('system:record:edit')")
    @PreAuthorize("@ss.hasAnyRoles('custom_admin,custom_common,custom_seller')")
    @Log(title = "代理发放记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProxyRecord proxyRecord) {
        return toAjax(proxyRecordService.updateProxyRecord(proxyRecord));
    }

    /**
     * 删除代理发放记录
     */
//    @PreAuthorize("@ss.hasPermi('system:record:remove')")
    @PreAuthorize("@ss.hasAnyRoles('custom_admin,custom_common,custom_seller')")
    @Log(title = "代理发放记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(proxyRecordService.deleteProxyRecordByIds(ids));
    }

//    @PreAuthorize("@ss.hasAnyRoles('custom_admin,custom_common,custom_seller')")
//    @PostMapping("/create_records")
//    public AjaxResult createRecords(ProxyRecord proxyRecord) {
//        List<ProxyRecord> list = proxyRecordService.selectProxyRecordList(new ProxyRecord());
//        for (ProxyRecord record : list) {
//            proxyRecordService.deleteProxyRecordById(record.getId());
//        }
//
//        List<PlayerCostLog> playerCostLogList = playerCostLogService.selectPlayerCostLogList(new PlayerCostLog());
//        Collections.sort(playerCostLogList, Comparator.comparing(PlayerCostLog::getTime));
//
//        List<Franchiser> allFranchiserList = franchiserService.selectFranchiserList(new Franchiser());
//
//        Franchiser lv1Franchiser = Helper.getLv1Franchiser(allFranchiserList);
//
//        for (PlayerCostLog playerCostLog : playerCostLogList) {
//            long franchiserId = playerCostLog.getFranchiserId();
//            List<Franchiser> franchiserList = Helper.getAllFranchiserList(allFranchiserList, franchiserId);
//            List<Franchiser> mixFranchiserList = Helper.getMixFranchiser(allFranchiserList, RandomUtils.nextInt(1, 3));
//            Franchiser franchiser = Helper.getFranchiser(allFranchiserList, franchiserId);
//
//            long costValue = playerCostLog.getSliver() * 10;
//
//            for (int i = 0; i < franchiserList.size(); i++) {
//                long value = 0;
//                if (i == franchiserList.size() - 1) {
//                    value = costValue;
//                } else {
//                    value = RandomUtils.nextLong(1, costValue - franchiserList.size());
//                }
//                costValue = costValue - value;
//
//                Franchiser sendFranchiser = franchiserList.get(i);
//                ProxyRecord record = new ProxyRecord();
//                // 代理id
//                record.setFranchiserId(lv1Franchiser.getFranchiserId());
//                record.setName(lv1Franchiser.getName());
//                record.setTargetId(sendFranchiser.getFranchiserId());
//                record.setTargetName(sendFranchiser.getName());
//                record.setValue(value);
//                record.setTime(playerCostLog.getTime());
//                proxyRecordService.insertProxyRecord(record);
//            }
//            // 混淆供应商
//            long costValueB = playerCostLog.getSliver() * 10 * RandomUtils.nextLong(10, 50) / 100;
//            for (int i = 0; i < mixFranchiserList.size(); i++) {
//                long value = 0;
//                if (i == mixFranchiserList.size() - 1) {
//                    value = costValueB;
//                } else {
//                    value = RandomUtils.nextLong(1, costValueB - mixFranchiserList.size());
//                }
//                costValueB = costValueB - value;
//
//                Franchiser sendFranchiser = mixFranchiserList.get(i);
//                ProxyRecord record = new ProxyRecord();
//                record.setFranchiserId(lv1Franchiser.getFranchiserId());
//                record.setName(lv1Franchiser.getName());
//                record.setTargetId(sendFranchiser.getFranchiserId());
//                record.setTargetName(sendFranchiser.getName());
//                record.setValue(value);
//                record.setTime(playerCostLog.getTime());
//                proxyRecordService.insertProxyRecord(record);
//            }
//        }
//
//        return success();
//    }
}
